<template>
  <transition name="bounce" mode="out-in">
    <div class="mui-content mh-login-container">
      <img class="login-bg" src="../../assets/images/bg/bg.png">
      <div class="form-box">
        <div class="login-head mui-text-center">
          <a
            class="lr-link"
            :class="{active: activeForm}"
            href="javascript:"
            @click="toggleLogReg"
          >
            登录
          </a>
          <span>|</span>
          <a
            class="lr-link"
            href="javascript:"
            :class="{active: !activeForm}"
            @click="toggleLogReg"
          >注册</a>
        </div>
        <div v-show="activeForm">
          <form class="mui-input-group login-form">
            <div class="mui-input-row">
              <input type="text" class="mui-input-clear" v-model="loginForm.phone" placeholder="请输入手机号">
            </div>
            <div class="mui-input-row">
              <input type="password" class="mui-input-password" v-model="loginForm.pwd" placeholder="请输入密码" autocomplete="false">
            </div>
            <div class="mui-input-row">
              <input type="text" class="mui-input-clear" v-model="loginForm.msgCode" placeholder="请输入验证码">
              <button v-if='codeFlag' type="button" class="captcha send-btn" @click='getCode(1)'>发送验证码</button>
              <span v-else class="captcha code-time">重新获取{{time}}s</span>
            </div>
          </form>
          <div class="mui-content-padded lg-btn-box">
            <button type="button" id="loginBtn" class="mui-btn-block login-btn" data-loading-text = "登入中..." @tap="login">
              登录
            </button>
            <p class="forgot-link"><router-link to="/account/password">忘记密码？</router-link></p>
          </div>
        </div>
        <div v-show="!activeForm">
          <form class="mui-input-group login-form">
            <div class="mui-input-row">
              <input type="text" class="mui-input-clear" v-model="regForm.phone" placeholder="请输入手机号" autocomplete="false">
            </div>
            <div class="mui-input-row">
              <input type="password" class="mui-input-password" v-model="regForm.pwd" placeholder="请设置6-12位密码" autocomplete="false">
            </div>
            <div class="mui-input-row">
              <input type="text" class="mui-input-clear" v-model="regForm.msgCode" placeholder="请输入验证码">
              <button v-if='codeFlag' type="button" class="captcha send-btn" @click='getCode(2)'>发送验证码</button>
              <span v-else class="captcha code-time">重新获取{{time}}s</span>
            </div>
            <div class="mui-input-row">
              <input type="text" class="mui-input-clear" v-model="regForm.recId" placeholder="请输入推荐人ID/昵称/手机号/微信">
            </div>
          </form>
          <p class="service-items">已阅读和同意<a>《服务协议》</a>和<a>《个人信息保护条款》</a></p>
          <div class="mui-content-padded lg-btn-box">
            <button type="button" id="regBtn" class="mui-btn-block login-btn" data-loading-text = "注册中..." @click="regAccount">注册</button>
          </div>
          <input id="sharecontent" type="hidden" value="测试分享内容">
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
import MhIdentify from '@/components/identify/identify'
import {MH_API} from "@/api/api";
import md5 from 'js-md5';

let shares = null;
export default {
  name: "login",
  data () {
    return {
      activeForm: true,
      identifyCode: '',
      identifyCodes: '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
      loginForm: {
        phone: '18252740439',
        pwd: '123456',
        msgCode: ''
      },
      regForm: {
        phone: '18252740439',
        pwd: '123456',
        msgCode: '',
        recId: ''
      },
      codeFlag: true,
      time: 60,
      latitude: '30.2799186759',
      longitude: '120.1617445782',
      cid: null
    }
  },
  beforeCreate() {

  },
  mounted () {
    let self = this;
    mui.plusReady(function () {
      //定位
      plus.geolocation.getCurrentPosition(function(res) {
        //成功回调
        //console.log(1)
        console.log(JSON.stringify(res))
        console.log(JSON.stringify(res.coords))
        let city = res.address.city;
        city = city.replace(/市/,'');
        let user_latitude = res.coords.latitude; //纬度
        let user_longitude = res.coords.longitude; //经度
        //console.log("经度："+user_longitude+" 纬度："+user_latitude);
        self.latitude = user_latitude;
        self.longitude = user_longitude;
        window.localStorage.setItem("user_lat", user_latitude);
        window.localStorage.setItem("user_lng", user_longitude);
        window.localStorage.setItem("city", city);
      }, function(e) {
        console.log('Gelocation Error: code - ' + e.code + '; message - ' + e.message);
        switch(e.code) {
          case 10:
            mui.alert('请开启应用的定位权限', '温馨提示','确定',function(){},'div');
            break;
          case 9:
            //mui.alert('请开启手机定位服务');
            mui.alert('请开启手机定位服务', '温馨提示','确定',function(){},'div');
            break;
          case 2:
            if(e.message.indexOf("[geolocation:13]") > -1) { 
              //如果网络开启，定位失败，提示检查定位权限
              mui.alert('请开启应用的定位权限', '温馨提示','确定',function(){},'div');
            }
            if(e.message.indexOf("[geolocation:14]") > -1) { 
              //如果应用的权限开了，提示网络异常
              mui.alert('请检查网络是否正常', '温馨提示','确定',function(){},'div');
            }
            break;
          case e.PERMISSION_DENIED:
            mui.alert('请求定位被拒绝', '温馨提示','确定',function(){},'div');
            break;
          case e.POSITION_UNAVAILABLE:
            mui.alert("位置信息不可用", '温馨提示','确定',function(){},'div');
            break;
          case e.TIMEOUT:
            mui.alert("获取位置信息超时", '温馨提示','确定',function(){},'div');
            break;
          case e.UNKNOWN_ERROR:
            mui.alert("未知错误", '温馨提示','确定',function(){},'div');
            break;
        }
      }, {
        //超时未获取到经纬度信息  执行失败回调  (默认为5秒)
        timeout: 3000
      })

      //推送
      // 页面加载时触发  
      var pinf = plus.push.getClientInfo();  
      console.log(JSON.stringify(pinf))
      var cid = pinf.clientid;//客户端标识
      console.log("cid："+cid)
      if(cid){
        window.localStorage.setItem("cid", cid);
      }
      self.cid = cid;
      //mui.alert(cid)
      //监听系统通知栏消息点击事件  
      plus.push.addEventListener('click', function(msg){  
          //mui.alert(msg)
          //处理点击消息的业务逻辑代码  
      }, false);  
      //监听接收透传消息事件  
      plus.push.addEventListener('receive', function(msg){  
          console.log(msg)
          //处理透传消息的业务逻辑代码  
      }, false);

      //分享
      plus.share.getServices(function(s) {  
        shares={};
        for(var i in s){
          var t=s[i];
          shares[t.id]=t;
        }
      }, function(e) {  
        console.log("获取分享服务列表失败：" + e.message);  
      });

    })

    this.refreshCode()
  },
  methods: {
    getCode(type){
      let phone = this.loginForm.phone;
      if(type==2){
        phone = this.regForm.phone;
      }
      if (!phone) {
        mui.toast('请输入手机号');
        return false;
      }
      let self = this;
      MH_API.sendCode({
        phone: phone
      }).then(res => {
        //if (res.code === 200) {
          self.codeFlag = false;
          mui.toast("发送成功");
          let time = self.time;
          let timer = setInterval(function(){
            --time;
            if(time==0){
              time = 60;
              clearInterval(timer);
              self.codeFlag = true;
            }
            self.time = time;
          }, 1000)
        //}
      })
    },
    toggleLogReg () {
      this.activeForm = !this.activeForm;
    },
    makeCode (o, l) {
      let _that = this;
      for (let i  = 0; i < l; i++) {
        _that.identifyCode += _that.identifyCodes[
          _that.randomNum(0, _that.identifyCodes.length)
          ]
      }
    },
    refreshCode () {
      this.identifyCode = '';
      this.makeCode(this.identifyCodes, 4);
    },
    randomNum (min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
    login () {
      let self = this;
      // MH_API.putMsg({
      //   cid: window.localStorage.setItem("cid"),
      //   type: 1
      // }).then(res => {
      //   if (res.status == 200) {
      //     console.log("推送成功")
      //   }
      //   else{
      //     console.log(res.msg)
      //   }
      // })
      //let identifyLower = this.identifyCode.toLowerCase();
      //let validateLower = this.loginForm.validateCode.toLowerCase();
      mui('#loginBtn').button('loading');
      if (!this.loginForm.phone) {
        mui.toast('请输入手机号');
        mui('#loginBtn').button('reset');
        return false;
      } else if (!this.loginForm.pwd) {
        mui.toast('请输入密码');
        mui('#loginBtn').button('reset');
        return false;
      } else if (!this.loginForm.msgCode) {
        mui.toast('请输入验证码');
        mui('#loginBtn').button('reset');
        return false;
      } 
      // else if (validateLower !== identifyLower) {
      //   mui.toast('验证码不正确');
      //   mui('#loginBtn').button('reset');
      //   return false;
      // }
      let params = {
        username: this.loginForm.phone,
        //password: md5(this.loginForm.pwd)
        password: this.loginForm.pwd,
        code: this.loginForm.msgCode,
        latitude: this.latitude,
        longitude: this.longitude
      };
      MH_API.serverLogin(params).then(res => {
        if (res.status === 200) {
          mui.toast('登录成功');
          mui('#loginBtn').button('reset');
          res.token && window.localStorage.setItem("token", res.token);
          res.user_id && window.localStorage.setItem("userid", res.user_id);
          window.localStorage.setItem("phone", this.loginForm.phone);

          res.jurisdiction && window.localStorage.setItem("vip", JSON.stringify(res.jurisdiction));

          //传经纬度
          MH_API.putPosition({
            latitude: self.latitude,
            longitude: self.longitude
          }).then(res => {
            if (res.status == 200) {

            }
          })

          if(res.is_hong==1){
            this.$router.push({path: '/maker/matcher'})
          }
          else{
            this.$router.push({path: '/meet'})
          }
        }
        else{
          mui.toast(res.msg);
          mui('#loginBtn').button('reset');
        }
      })
    },
    regAccount () {
      mui('#regBtn').button('loading');
      if (!this.regForm.phone) {
        mui.toast('请输入手机号');
        mui('#regBtn').button('reset');
        return false;
      } else if (!this.regForm.pwd) {
        mui.toast('请输入密码');
        mui('#regBtn').button('reset');
        return false;
      } else if (!this.regForm.msgCode) {
        mui.toast('请输入验证码');
        mui('#regBtn').button('reset');
        return false;
      } 
      let params = {
        phone: this.regForm.phone,
        //password: md5(this.loginForm.pwd)
        password: this.regForm.pwd,
        recommend: this.regForm.recId,
        code: this.regForm.msgCode
      };
      MH_API.serverRegist(params).then(res => {
        if (res.status === 200) {
          mui.toast('注册成功');
          mui('#regBtn').button('reset');
          this.regForm = {
            phone: '',
            pwd: '',
            msgCode: '',
            recId: ''
          };
          res.token && window.localStorage.setItem("token", res.token);
          res.user_id && window.localStorage.setItem("userid", res.user_id);
          this.$router.push({path: '/account/completeMaterial'})
        }
        else{
          mui.toast(res.msg);
          mui('#regBtn').button('reset');
        }
      })
    }
  },
  components: {
    MhIdentify
  },
  created(){
    let qiniu = require('qiniu');
    var accessKey = 'W-2EW4PaVB1fqVxtZAOS0r2u6zLMZ0TQGPoJ1IqN';
    var secretKey = 'YEqiHprqvI2QE6xfFs0QFeUTDARtQaojCqBJf9IP';
    var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    var options = {
      scope: 'mh_app',
      expires: 72000
    };
    var putPolicy = new qiniu.rs.PutPolicy(options);
    var uploadToken=putPolicy.uploadToken(mac);
    console.log(uploadToken)
    if(uploadToken){
      window.localStorage.setItem("uploadToken", uploadToken);
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../../assets/css/mixin";
.mh-login-container {
  position: relative;
  height: 100%;
  padding: 1px;
  background-color: #fff;
  background-size: 100% 100%;
}
.login-bg{ position: absolute; top:0; left:0; width:100%; z-index:1;}
.form-box {
  width: 92%;
  margin: 25% auto 0; position:relative; z-index:100;
}
.login-head {
  margin: 0 0 5rem;
  &>span {margin: 0 .4rem;}
}
.lr-link {
  font-size: 1.5rem;
  &.active {font-size: 2.4rem;}
  &:hover {color: #333;}
}
.lg-btn-box {
  margin-top: 3rem;
}
.login-form {
  margin: 2rem;
}
.login-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e685aa;
  border-radius: .5rem;
  letter-spacing: 2px;
  color: #fff;
  span {color: #fff;}
}
.captcha {
  @include ct;
  padding: 0;
  background: #e685aa;
  right: 0;
  border-radius: .5rem;
  color: #fff;
  &:hover {
    background: #e685aa;
  }
}
.code-time{ display:inline-block; background-color:#ccc;padding: .8rem 1rem;}
.send-btn {
  padding: .8rem 1rem;
}
.mui-input-group .mui-input-row {height: 5rem;}
.mui-input-group:before,.mui-input-group:after {height: 0;}
.mui-input-group .mui-input-row:after {background: #eee;}
.login-form {
  input[type=text],
  input[type=password] {
    height: 5rem;
    padding-left: 0;
  }
}
.forgot-link {
  margin-top: 1.6rem;
  text-align: center;
  a {
    font-size: 1.5rem;
  }
}
.service-items {
  margin: 0 10px;
  font-size: 1.2rem;
  color: #333;
  a {color: #2381fd;}
}
</style>
